package com.pox.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pox.guli.service.edu.entity.Subject;
import com.pox.guli.service.edu.entity.excel.SubjectExcel;
import com.pox.guli.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author PoX21s
 * @Date: 2022/6/3 15:18
 * @Version 1.0
 */

@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EasyExcelListener extends AnalysisEventListener<SubjectExcel> {

    private SubjectMapper subjectMapper;

    @Override
    public void invoke(SubjectExcel subjectExcel, AnalysisContext analysisContext) {

        log.info("读取到的每条数据：" + subjectExcel.toString());
        // 获取读取到的数据
        String levelOneTitle = subjectExcel.getLevelOneTitle();
        String levelTwoTitle = subjectExcel.getLevelTwoTitle();

        /*
         * 将读取的数据存储到数据库中
         * */
        // 组装一级分类
        Subject oneTitleByTitle = this.getOneTitleByTitle(levelOneTitle);
        String parentId = null;

        if (oneTitleByTitle == null) {
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            // 添加到数据库
            subjectMapper.insert(subject);

            parentId = subject.getId();
        } else {
            parentId = oneTitleByTitle.getId();
        }

        // 组装二级标题
        Subject twoTitleByTitle = this.getTwoTitleByTitle(parentId, levelTwoTitle);
        if (twoTitleByTitle == null) {
            Subject subject = new Subject();
            subject.setParentId(parentId);
            subject.setTitle(levelTwoTitle);

            subjectMapper.insert(subject);
        }

    }

    /**
     * 数据解析完后执行
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成！");
    }

    /**
     * 查询当前一级标题是否存在于数据库中
     *
     * @param levelOneTitle 查询的一级标题
     * @return com.pox.guli.service.edu.entity.Subject
     */
    public Subject getOneTitleByTitle(String levelOneTitle) {

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", levelOneTitle)
                // 查询是否为一级标题
                .eq("parent_id", "0");

        return subjectMapper.selectOne(queryWrapper);
    }

    /**
     * 查询传入二级标题是否在当前一级标题下存在
     *
     * @param parentId      指定的一级标题
     * @param levelTwoTitle 查询的二级标题
     * @return com.pox.guli.service.edu.entity.Subject
     */
    public Subject getTwoTitleByTitle(String parentId, String levelTwoTitle) {

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", levelTwoTitle)
                .eq("parent_id", parentId);

        return subjectMapper.selectOne(queryWrapper);
    }
}
